
layui.define(['table', 'form'], function(exports){
	
	  var $ = layui.$
	  ,table = layui.table
	  ,setter = layui.setter
	  ,common = layui.common
	  ,form = layui.form;
	  
	  var parentJson = {};
	  
	  var obj = {
			setParentJson: function setParentJson(json){
				parentJson = json;
		 	} 
	  }
	  var colsArr;
	  var tableTitle;
	  var tableField; //表头字段
	  var tableSearch = [];//全局搜索条件
	  var tableHead;//表头字段
	  $.ajax({
	      url: setter.host+'/adminmanager/user/getSelectHead'
	      ,type:'get'
	      ,dataType:'json'
	      ,success: function(res){
	        //请求成功后
	    	if(res.status == setter.response.statusCode.status_Success){
		      	  loadTable(res.data.field);
	        }else{
	        	window.location.href = setter.host+'/error/toNoPower?msg='+res.msg;
	        }
	      }
	    });
	  $('.layui-btn').on('click', function(){
  	    var type = $(this).data('type');
  	    active[type] ? active[type].call(this) : '';
  	  });
	  
	  var jobNumTpl = function(d){
		    return '<a lay-event="lookUp" style="cursor: pointer" ><span  style="color:#1E9FFF">'+d.userId+'</span></a>';
		  };
	  function loadTable(header){
		  colsArr = [
	  				{type: 'checkbox', fixed: 'left'},
	  				{field: 'groupId', title: '组织机构',sort:true,align:'center',hide:true},
	  				{field: 'groupname', title: '组织机构',sort:true,align:'center'},
	  	            {field: 'userId', title: '用户号',templet: jobNumTpl,sort:true,align:'center',width: 100, sort: true,hide:(header.search("userId") == -1)},
	  	            {field: 'username', title: '用户名',align:'center',sort:true,sort: true,width: 130,hide:(header.search("username") == -1)},
	  	            {field: 'password', title: '密码',align:'center',sort:true,hide:(header.search("password") == -1)},
	  	            {field: 'command', title: '口令',align:'center',sort:true, hide:(header.search("command") == -1)},
	  	            {field: 'name', title: '姓名', align:'center',sort:true,hide:(header.search("name") == -1)},
	  	            {field: 'sex', title: '性别',align:'center',sort:true,templet: '#buttonPlace', width: 130,hide:(header.search("sex")== -1)},
	  	            {field: 'phone', title: '手机号',align:'center',sort:true,sort: true, width: 180,hide:(header.search("phone") == -1)},
	  	            {field: 'jobnumber', title: '工号',align:'center',sort:true, hide:(header.search("jobnumber") == -1)},
	  	            {field: 'company', title: '钉钉组织',align:'center',sort:true, hide:(header.search("company") == -1),templet: function(d){
	      			  if(d.company=='jindushenghuo'){return '金度生活'}else if(d.company=='qiyegongzuo'){'企业工作'}else{return '手动添加'}     
	    		      }
	  	            },
	  	            {field: 'remark', title: '备注',align:'center',sort:true,sort: true, width: 180,hide:(header.search("remark") == -1)},
	  	            {field: 'mail', title: '邮箱',align:'center',sort:true, hide:(header.search("mail") == -1)},
	  	            {field: 'status', title: '状态',align:'center',sort:true, templet: '#statusTpl', width: 80,hide:(header.search("status") == -1)}
	  	        ];
			layui.each(colsArr,function(inx,val){
				tableHead += val.hasOwnProperty('field')?val.field:'-';
				tableHead += ',';
				tableTitle += val.hasOwnProperty('title')?(val.hide?'':val.title+','):',';
				tableField += val.hasOwnProperty('field')?(val.hide?'':val.field+','):',';
		   	})
		   	//tableHead是获取表字段
	   		tableHead = tableHead.substring(tableHead.indexOf(',')+1,tableHead.length-1);
			//导出时需要用到标题
			tableTitle = tableTitle.substring(tableTitle.indexOf(',')+1,tableTitle.length-1);
			//导出需要用到实际导出的字段
			tableField = tableField.substring(tableField.indexOf(',')+1,tableField.length-1);
			
		  //用户管理
		  table.render({
		    elem: '#LAY-user-manage'
		    ,url: setter.host + '/adminmanager/user/getSelectBody' 
		    ,cols: [colsArr]
		    //,toolbar: 'true'
			//,defaultToolbar: ['print']
		  	,method:'post'
		  	,contentType:'application/json; charset=utf-8'
		  	,where:{'headField':tableHead}
		    ,page: true
		    ,groups:2
		    ,limit: 15
		    ,limits:[15,30,50]
		    ,height: 'full-60'
	    	,text: {
	    	    none: '暂无相关数据' 
			}
			,done:function () {
				delete this.where; 
			}
		  });
	  }
	 
	//事件
	  var active = {
	    batchdel: function(){
	      var checkStatus = table.checkStatus('LAY-user-manage')
	      ,checkData = checkStatus.data; 

	      if(checkData.length === 0){
	        return layer.msg('请选择数据');
	      }
	      layer.prompt({
	        formType: 1
	        ,title: '敏感操作，请验证口令'
	      }, function(value, index){
	    	var command = layui.sessionData('layuiSession').command;
	    	if(value == command){
	          	layer.close(index);
	          	layer.confirm('确定删除吗？', function(index_confirm) {
			        layer.close(index_confirm);
			        var delIds ={'delData':[]};
			        layui.each(checkData,function(inx,checkValue){
			        	var delId = {};
			        	delId.jobNum = checkValue.jobNum;
			        	delIds.delData.push(delId);
		  		    })
		  		    //console.log(JSON.stringify(delIds));
		  		 	$.ajax({
	        	        url: setter.host+'/adminmanager/user/batchdel'
	        	        ,type:'post'
	        	        ,dataType:'json'
	        	        ,contentType: "application/json; charset=utf-8"
	        	        ,data:JSON.stringify(delIds)
	        	        ,success: function(res){
	        	          //请求成功后
	        	          if(res.status == setter.response.statusCode.status_Success){
	        	        	 table.reload('LAY-user-manage'); 
	        	        	  layer.msg(res.msg);
	            			  layer.close(index);
	        	          }else{
	        	        	  layer.msg(res.msg);
	        	          }
	        	        }
	        	      });
		          });
	        	}else{
	        		layer.msg('口令错误');
	        	}
	      });
	    }
	    ,add: function(){
	    	layer.load(1, {
	    		  shade: [0.1,'#fff'] //0.1透明度的白色背景
	    		})
	    	layui.admin.req({
				url: setter.host+'/dingding/ddUserinTUser'
				,type:'get'
				,dataType:'json'
				,contentType: "application/json; charset=utf-8"
//				,data:JSON.stringify(field) 
				,done: function(res){
				//请求成功后
//					if(res.status == setter.response.statusCode.status_Success){
//						layer.msg(res.msg,{time:1000},function(){
//							backUrl();
//						});
//					}else{
//					}
					layer.closeAll();
					layer.msg(res.msg);
				}
			});
	    }
	    ,addmendian: function(){
	    	layer.load(1, {
	    		  shade: [0.1,'#fff'] //0.1透明度的白色背景
	    		})
	    	layui.admin.req({
				url: setter.host+'/dingding/ddMendianUserinTUser'
				,type:'get'
				,dataType:'json'
				,contentType: "application/json; charset=utf-8"
//				,data:JSON.stringify(field) 
				,done: function(res){
				//请求成功后
//					if(res.status == setter.response.statusCode.status_Success){
//						layer.msg(res.msg,{time:1000},function(){
//							backUrl();
//						});
//					}else{
//					}
					layer.closeAll();
					layer.msg(res.msg);
				}
			});
	    }
	    ,addqiye2: function(){
	    	layer.load(1, {
	    		  shade: [0.1,'#fff'] //0.1透明度的白色背景
	    		})
	    	layui.admin.req({
				url: setter.host+'/dingding/ddqiye2UserinTUser'
				,type:'get'
				,dataType:'json'
				,contentType: "application/json; charset=utf-8"
//				,data:JSON.stringify(field) 
				,done: function(res){
				//请求成功后
//					if(res.status == setter.response.statusCode.status_Success){
//						layer.msg(res.msg,{time:1000},function(){
//							backUrl();
//						});
//					}else{
//					}
					layer.closeAll();
					layer.msg(res.msg);
				}
			});
	    }
	    ,addUser: function(){
	    	var obj = {};
	    	obj.bakUrl = setter.host+'/adminmanager/user/toSelect';
	    	obj.modifyType = 'add';
	    	layui.common.postUrl(obj,setter.host+'/adminmanager/user/toEdit');
	    }
	    ,edit: function(){
	      var checkStatus = table.checkStatus('LAY-user-manage')
  	      ,checkData = checkStatus.data; 

  	      if(checkData.length === 0){
  	        return layer.msg('请选择数据');
  	      }
  	      if(checkData.length > 1){
    	        return layer.msg('只能编辑一行数据');
    	  }
  	      checkData[0].bakUrl = setter.host+'/adminmanager/user/toSelect';
  	      layui.common.postUrl(checkData[0],setter.host+'/adminmanager/user/toEdit');
  	  	}
	    ,exportExcel: function(){
	  		  var where = {};
	  		  where.search=JSON.stringify(tableSearch);
	  		  where.format = "excel";
	  		  where.title = tableTitle;
	  		  where.field = tableField;
	  		  layui.common.postUrl(where, setter.host+'/adminmanager/user/exportExcel');
		 }	  
	    ,exportCsv: function(){
	    	var where = {};
	    	where.whereKey=JSON.stringify(tableSearch);;
	    	where.format = "csv";
	    	where.title = tableTitle;
	    	where.field = tableField;
	    	layui.common.postUrl(where, setter.host+'/adminmanager/user/exportExcel');
	    }	  
	    ,exportPdf: function(){
	    	layer.msg('暂不支持');
	    }	  
	    ,exportWord: function(){
	    	layer.msg('暂不支持');
	    }	  
	  };
	  //监听排序工具条
	  table.on('sort(LAY-user-manage)', function(obj){
		 
		  //尽管我们的 table 自带排序功能，但并没有请求服务端。
		  //有些时候，你可能需要根据当前排序的字段，重新向服务端发送请求，从而实现服务端排序，如：
		  table.reload('LAY-user-manage', {
		    initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。
		    ,where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
		      ascField: obj.field //排序字段
		      ,asc: obj.type //排序方式
		      ,headField:tableHead //表头字段
		      ,search: tableSearch //查询字段
		    }
		  });
	  });
	  table.on('tool(LAY-user-manage)', function(obj){
			 obj.data.bakUrl = setter.host+'/adminmanager/user/toSelect';
			 if(obj.event=='lookUp'){
				 layui.common.postUrl(obj.data,setter.host+'/adminmanager/user/toEdit');
			 }
	  });
	  
	  //监听搜索
	  form.on('submit(LAY-user-normal-search)', function(data){
		var search = {};
		console.log(data)
		search.conditionField = data.field.whereKey;
		search.conditionValue = data.field.whereValue;
		search.conditionOption = 'like';
		tableSearch[0] = search;
//		tableSearch[data.field.whereKey] = data.field.whereValue;
	    //执行重载
	    table.reload('LAY-user-manage', {
	    	where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
	    		search: tableSearch //查询字段
	    		,headField:tableHead //表头字段
	    		,page:1//页码取第一页
			}
	    });
	  });
	  //监听搜索
	  form.on('submit(LAY-user-gread-search)', function(data){
	    layer.msg('暂不支持');
	  });
	  
	  exports('select', {})
});